package com.loser.gateway;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.loser.utils.trace.MDCUtil;
import com.loser.utils.trace.TraceUtil;
import feign.RequestInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@SpringBootApplication
@EnableScheduling
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplicationBuilder().sources(ApiGatewayApplication.class).build();
        springApplication.setWebApplicationType(WebApplicationType.NONE);
        springApplication.run(args);
    }

    @Bean
    public RequestInterceptor headerInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            String traceId = request.getHeader(MDCUtil.TRACE_ID);
            if (StringUtils.isEmpty(traceId)) {
                traceId = MDCUtil.getTraceId();
                if (StringUtils.isEmpty(traceId)) {
                    traceId = TraceUtil.getTraceId();
                }
            }
            requestTemplate.header(MDCUtil.TRACE_ID, traceId);
        };
    }

}
